package com.onlineauction.servlets;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.onlineauction.entities.Auction;
import com.onlineauction.entities.Bid;
import com.onlineauction.helpers.Constants;

public class ConfirmBidServlet extends HttpServlet {

	private static final long serialVersionUID = -1134952609601991574L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {
		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute(Constants.USERNAME);

		// user not logged in
		if (username == null) {
			response.sendRedirect("/LoginAccount");
			return;
		}

		double bidPrice = -1.0;
		long auctionID = -1L, itemID = -1L;

		try {
			itemID = Long.parseLong(request.getParameter(Constants.ITEM_ID));
			auctionID = Long.parseLong(request.getParameter(Constants.AUCTION_ID));
			bidPrice = Double.parseDouble(request.getParameter(Constants.BID_PRICE));
		} catch (Exception e) {
			// do nothing
		}

		if (itemID < 0) {
			response.sendRedirect("/Home");
			return;
		}

		if (auctionID < 0) {
			request.getRequestDispatcher("/confirmBid.jsp").forward(request, response);
			return;
		}

		boolean isPriceValid = true;
		Auction auction = new Auction(auctionID);
		if (bidPrice < auction.getAskPrice()) {
			isPriceValid = false;
		}

		Bid bestBid = Bid.getBestBidOfAuction(auctionID);
		if (bestBid != null && bestBid.getBidPrice() >= bidPrice) {
			isPriceValid = false;
		}

		if (!isPriceValid) {
			String message = "The bid price you entered is not valid.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/confirmBid.jsp?" + Constants.ITEM_ID + "=" + itemID)
					.forward(request, response);
			return;
		}
		
		if (bestBid != null && bestBid.getUsername().equals(username)) {
			String message = "You already hold the best bid, so you don't need to bid again.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/confirmBid.jsp?" + Constants.ITEM_ID + "=" + itemID)
					.forward(request, response);
			return;
		}

		Date now = new Date();
		Bid newBid = new Bid(auctionID, username, now, bidPrice, true);
		String message = "You have successfully made the bid!";
		request.setAttribute(Constants.MESSAGE, message);
		request.getRequestDispatcher("/confirmBid.jsp?" + Constants.ITEM_ID + "=" + itemID)
				.forward(request, response);
		return;

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doGet(request, response);
	}

}
